<!--货品信息-->
<template>
    <el-form :model="procform" ref="procref" :inline="true" style="text-align: left;">
        <el-form-item label="货品名称:" prop="name">
            <el-input placeholder="请输入货品名称" v-model="procform.name"></el-input>
        </el-form-item>
        <el-form-item label="仓库" prop="whid">
            <el-select placeholder="请选择" v-model="procform.whid" style="width:200px">
                <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="货品分类" prop="type">
            <el-tree-select v-model="procform.type" :data="types"
                    :props="{
                        value: 'type_id',
                        label: 'type_name',
                        children: 'children'
                    }"
                    placeholder="请选择"
                    style="width: 200px"
                    check-strictly
                    default-expand-all/>
        </el-form-item>
         <el-form-item label="单位" prop="unit">
            <el-select placeholder="请选择" v-model="procform.unit" style="width:200px">
                <el-option v-for="item in units" :key="item.dict_label" :label="item.dict_label" :value="item.dict_label"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
            <el-select placeholder="请选择" v-model="procform.status" style="width:200px" @change="filterByStatus">
                <el-option v-for="item in status" :key="item.dict_label" :label="item.dict_label" :value="item.dict_label"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button @click="Export">导出</el-button>
        <el-button @click="Refresh">刷新</el-button>
    </div>
    <!--表格-->
    <el-table :data="procdata" stripe style="margin-top: 10px;"  @selection-change="SelectChange">
        <el-table-column fixed  type="selection"></el-table-column>
        <el-table-column fixed  type="index" label="序号" width="70px"></el-table-column>
        <el-table-column fixed  label="货品编号" width="150px">
            <template #default="scope">
                <span style="color: green;cursor: pointer;" @click="ShowInfo(scope.row)">{{ scope.row.proc_code }}</span>
            </template>
        </el-table-column>
        <el-table-column fixed prop="proc_name" label="货品名称" width="150px"></el-table-column>
        <el-table-column fixed label="状态" width="100px">
            <template #default="scope">
                <span :style="{ 
                    color: scope.row.remaining_days <= 0 ? 'red' : 
                           scope.row.remaining_days <= 7 ? 'red' : 
                           scope.row.remaining_days <= 30 ? 'orange' : 'green' 
                }">
                    {{ scope.row.remaining_days <= 0 ? '已过期' : 
                       scope.row.remaining_days <= 7 ? '即将到期' : 
                       scope.row.remaining_days <= 30 ? '正常' : '正常' }}
                </span>
            </template>
        </el-table-column>
        <el-table-column  prop="type_name" label="货品类型"></el-table-column>
        <el-table-column  prop="proc_model" label="规格型号"></el-table-column>
        <el-table-column  prop="proc_primary_unit" label="单位"></el-table-column>
        <el-table-column  prop="proc_primary_barcode" label="货品条码"></el-table-column>
        <el-table-column  prop="wh_name" label="仓库名称"></el-table-column>
        <el-table-column  prop="slot_name" label="库位名称"></el-table-column>
        <el-table-column  prop="stk_hand_num" label="当前库存"></el-table-column>
        <el-table-column  prop="proc_date" label="生产日期" width="200"></el-table-column>
        <el-table-column  prop="expiry_date" label="到期日期" width="200"></el-table-column>
        <el-table-column  prop="proc_expirationdate" label="保质期"></el-table-column>
        <el-table-column  prop="remaining_days" label="剩余天数">
            <template #default="scope">
                <span :style="{ color: scope.row.remaining_days <= 7 ? 'red' : scope.row.remaining_days <= 30 ? 'orange' : 'green' }">
                    {{ scope.row.remaining_days }}天
                </span>
            </template>
        </el-table-column>
    </el-table>

     <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

</template>

<script>
import {ref,reactive,onMounted } from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';//路由
import * as XLSX from 'xlsx';
export default {
setup()
    {
        const router = useRouter();//路由
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));
        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //查询所有仓库
        const warehouse=ref([]);
        function AllWarehouse(){
            http.get("/Warehouse/GetWarehouses")
            .then(res=>{
                warehouse.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有单位
        const units=ref([]);
        function Getunit(){
            http.get("/DictData/GetAllDictDataBytype?typeid=8")
            .then(res=>{
                units.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询状态
        const status=ref([]);
        function GetStatus(){
            http.get("/DictData/GetAllDictDataBytype?typeid=18")
            .then(res=>{
                status.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        //查询所有货品类型绑定到下拉框
        const types=ref([]);
        function AllType(){
            http.get("/ProductType/GetAllProductTypes")
            .then(res=>{
                types.value=convertToTree(res.data);
            }).catch(err=>{
                console.log(err);
            })
        }

         // 将扁平数据转换为树状结构的函数，同时保留所有相关节点及其父节点
         function convertToTree(data) {
            // 先创建一个以 type_id 为键的映射表，方便快速查找节点
            const map = {};
            data.forEach(item => {
                map[item.type_id] = { ...item, children: [] };
            });
            const tree = [];
            data.forEach(item => {
                const node = map[item.type_id];
                if (item.type_pid === 0) {
                    // 如果是顶层节点，直接添加到树中
                    tree.push(node);
                } else {
                    const parent = map[item.type_pid];
                    if (parent) {
                        // 如果父节点存在，将当前节点添加到父节点的 children 中
                        parent.children.push(node);
                    } else {
                        // 如果父节点不存在，将其作为顶层节点添加到树中
                        tree.push(node);
                    }
                }
            });
            return tree;
        }

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }
        //当前procid
        const procid=ref(0);

        //导出
        function Export(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "货品编号": row.proc_code,
                "货品名称": row.proc_name,
                "状态": row.remaining_days <= 0 ? '已过期' : 
                       row.remaining_days <= 7 ? '即将过期' : '正常',
                "货品类型": row.type_name,
                "规格型号": row.proc_model,
                "单位": row.proc_primary_unit,
                "货品条码": row.proc_primary_barcode,
                "仓库名称": row.wh_name,
                "库位名称": row.slot_name,
                "当前库存": row.stk_hand_num,
                "生产日期": row.proc_date,
                "到期日期": row.expiry_date,
                "保质期": row.proc_expirationdate + "天",
                "剩余天数": row.remaining_days + "天"
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "保质期查询");
            // 导出并下载
            XLSX.writeFile(wb, `保质期查询_${new Date().toLocaleDateString()}.xlsx`);
        }

    
        //#region 查询

        //表单数据
        const procref=ref("");
        const procform=reactive({
            name:"",
            type:"",
            inventory:false,
            whid:"",
            status:"" // 确保有这个字段
        })
        //表格数据
        const procdata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);

        //重置
        function Reset(){
            procref.value?.resetFields();
            All();
        }

        //查询
        function Search() {
            All();
        }

        //查询数据
        function All(){
            // 构建查询参数
            const params = {
                currentPage: currentPage.value,
                pageSize: 10
            };
            
            // 只有非空值才添加到参数中
            if (procform.name && procform.name.trim()) {
                params.productName = procform.name.trim();
            }
            
            if (procform.type && procform.type !== "") {
                params.productType = procform.type; // 后端期望的是int类型
            }
            
            if (procform.whid && procform.whid > 0) {
                params.warehouseId = procform.whid;
            }
            
            if (procform.unit && procform.unit.trim()) {
                params.unit = procform.unit.trim();
            }

            http.get("/Stock/GetShelfLifeQuery", { params })
            .then(res => {
                // 根据后端返回的数据结构调整
                if (res.data.success) {
                    rows.value = res.data.totalCount;
                    
                    if (res.data.data.length == 0) {
                        ElMessage({
                            message: '没有相关数据.',
                            type: 'warning',
                        })
                    }
                    
                    // 数据转换，计算到期日期和剩余天数
                    const Data = res.data.data.map(item => ({
                        ...item,
                        proc_date: item.proc_date ? formatDateTime(new Date(item.proc_date)) : '',
                        expiry_date: calculateExpiryDate(item.proc_date, item.proc_expirationdate),
                        remaining_days: calculateRemainingDays(item.proc_date, item.proc_expirationdate)
                    }));

                    // 保存原始数据
                    originalData.value = Data;
                    // 显示数据（应用当前状态过滤）
                    procdata.value = Data;
                    filterByStatus();
                } else {
                    ElMessage.error(res.data.Message || '获取数据失败');
                }
            }).catch(err => {
                ElMessage.error('获取数据失败');
                console.error('API错误详情:', err.response?.data);
                ElMessage.error(err.response?.data?.Message || '获取数据失败');
            })
        }

        // 添加计算到期日期的函数
        function calculateExpiryDate(procDate, expirationDays) {
            if (!procDate || !expirationDays) return '';
            
            const date = new Date(procDate);
            date.setDate(date.getDate() + parseInt(expirationDays));
            return formatDateTime(date);
        }

        // 添加计算剩余天数的函数
        function calculateRemainingDays(procDate, expirationDays) {
            if (!procDate || !expirationDays) return '';
            
            const productionDate = new Date(procDate);
            const expiryDate = new Date(productionDate);
            expiryDate.setDate(expiryDate.getDate() + parseInt(expirationDays));
            
            const today = new Date();
            const diffTime = expiryDate - today;
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            
            return diffDays > 0 ? diffDays : 0;
        }

        // 格式化日期函数（如果还没有的话）
        function formatDateTime(date) {
            if (!date) return '';
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }

        //#endregion

        //刷新
        function Refresh(){
            All();
        }

        // 添加原始数据存储
        const originalData = ref([]);

        // 根据剩余天数获取状态
        function getStatusByRemainingDays(remainingDays) {
            if (remainingDays <= 0) {
                return '已过期';
            } else if (remainingDays <= 7) {
                return '即将到期';
            } else {
                return '正常';
            }
        }

        // 状态过滤函数
        function filterByStatus() {
            console.log('当前选择的状态:', procform.status);
            console.log('原始数据长度:', originalData.value.length);
            
            if (!procform.status) {
                procdata.value = originalData.value;
                rows.value = originalData.value.length; // Update rows count for pagination
            } else {
                procdata.value = originalData.value.filter(item => {
                    const status = getStatusByRemainingDays(item.remaining_days);
                    console.log('货品状态:', status, '剩余天数:', item.remaining_days);
                    return status === procform.status;
                });
                rows.value = procdata.value.length; // Update rows count for pagination
            }
            
            console.log('过滤后数据长度:', procdata.value.length);
        }

        //挂载
        onMounted(() => {
            All();
            AllType();
            AllWarehouse();
            Getunit();
            GetStatus();
        });

        return{
            user,
            formatDateTime,
            procdata,
            procform,
            procref,
            Reset,
            Search,
            All,
            handlePageChange,
            rows,
            currentPage,
            types,
            AllType,
            selectdata,
            SelectChange,
            procid,
            Export,
            warehouse,
            Refresh,
            units,
            status,
            filterByStatus,
            originalData
        }
    }
}
</script>

<style scoped>

</style>
